import { ref, watchEffect } from 'vue';

export default function usePlatformImageLoader(
	gameImages: any,
	activeType: any,
	activePlatform: any,
	defaultPlatform: any,
	preloadLimit: number = 30,
	delayMs: number = 200
) {
	const loading = ref(false);
	const progress = ref(0);
	const errorPlatforms = ref<Set<string>>(new Set());
	let timer: any = null;
	// 核心预加载方法
	const preloadImages = async (platformKey: string) => {
		console.error(preloadImages)
		const target = gameImages.value[platformKey];
		if (!target || target.loaded) return;

		loading.value = true;
		// 仅取前N张图片
		const limitedImgs = target.imgs.slice(0, preloadLimit);
		const total = limitedImgs.length;
		let loadedCount = 0;
		// const startTime = Date.now().valueOf();
		try {
			await Promise.all(
				limitedImgs.map((url: any) =>
					new Promise((resolve, reject) => {
						const img = new Image();
						img.src = url;
						img.onload = () => {
							loadedCount++;
							progress.value = Math.round((loadedCount / total) * 100);
							resolve(url);
						};
						img.onerror = () => reject(new Error(`Failed to load: ${url}`));
					}).catch((e) => {
						errorPlatforms.value.add(platformKey);
						console.error(e);
					})
				)
			);
			target.loaded = true;
			// 设置同级的都为true
			Object.keys(activePlatform.value)?.forEach((key) => {
				if (gameImages.value[activePlatform.value[key]]) {
					gameImages.value[activePlatform.value[key]].loaded = true;
				}
			})
		} finally {
			// const endTime = Date.now().valueOf();
			// const _diff = endTime - startTime;
			// const baseTime = 800;
			// if (_diff < baseTime) {
			// 	setTimeout(() => {
			// 		loading.value = false;
			// 	}, baseTime - _diff)
			// } else {
			// 	loading.value = false;
			// }
			timer && clearTimeout(timer);
			timer = setTimeout(() => {
				loading.value = false;
			}, delayMs);
		}
	};

	// 自动监听活动平台变化
	watchEffect(() => {
		const currentPlatformKey = activePlatform.value?.[activeType.value];
		if (currentPlatformKey) {
			// preloadImages(currentPlatformKey);
		}
	});

	// 路由初始化处理
	const initFromRoute = () => {
		const routePlatformKey = `${activeType.value}-${defaultPlatform}`;
		if (routePlatformKey in gameImages.value) {
			// preloadImages(routePlatformKey);
		}
	};

	return { loading, progress, errorPlatforms, initFromRoute };
}
